<template>
	<view class="container">
		<!-- 顶部操作区 -->
		<view class="custom-card">
			<view class="card-title">箱操作</view>
			<view class="top-bar">
				<view class="box-text">总箱数：{{ this.boxes.length }}</view>
				<view class="box-actions">
					<u-button size="mini" type="primary" @click="clearAll" text="清空"></u-button>
					<!-- <u-button size="mini" type="primary" @click="switchBox" style="margin-left: 20rpx;" text="切换箱"></u-button> -->
					<!-- <u-button size="mini" type="success" @click="addBox" style="margin-left: 20rpx;" text="添加新箱"></u-button> -->
				</view>
			</view>
		</view>
		<u-picker :show="showPicker" :columns="boxPickerColumns" @confirm="confirmSwitchBox"
			@cancel="showPicker = false"></u-picker>

		<view class="custom-card">
			<view class="card-title">库位</view>
			<view class="location-row" @click="onShowLocation">
				<u-input v-model="form.locationName" placeholder="请选择库位或扫码" readonly class="location-input" />
				<u-icon name="scan" size="38" color="#2979ff" class="location-scan-icon" @click.stop="onScanLocation" />
			</view>
			<!-- 多选库位弹窗 -->
			<location-pop :show="showLocationPicker" @update:selectedIds="selectedLocationIds = $event"
				@close="showLocationPicker = false" @confirm="onLocationMultiConfirm" :locationList="locationList"
				:loading="loadingLoaction"></location-pop>
		</view>
		<!-- 扫码区 -->
		<!-- <view class="custom-card">
			<view class="card-title">扫码录入</view>
			<u-input placeholder="手动输入或扫码枪录入" v-model="barcodeInput" @confirm="addBarcode" clearable>
				<u-button slot="append" type="primary" @click="scanCode" text="扫码"></u-button>
			</u-input>
		</view> -->

		<!-- 箱信息区（卡片） -->
		<view class="custom-card">
			<view class="card-title">箱信息</view>
			<u-form :model="form" ref="uForm">
				<u-form-item label="箱号" label-width="80">
					<u-input v-model="form.cartons_no" placeholder="请输入/扫描唛头箱号" style="margin-right: 5px;"
						@change="onSearchSku" />
				</u-form-item>
				<u-form-item label="尺寸(cm)" label-width="80">
					<view class="dimension-input-row">
						<u-input v-model="form.cartons_length" type="number" placeholder="长" style="margin-right: 5px;"></u-input>
						<u-input v-model="form.cartons_width" type="number" placeholder="宽" style="margin-right: 5px;"></u-input>
						<u-input v-model="form.cartons_height" type="number" placeholder="高"></u-input>
					</view>
					<!-- TODO 样式调整 -->
					<!-- <view >采用客户尺寸</view> -->
				</u-form-item>
				<u-form-item label="重量(kg)" label-width="80">
					<u-input v-model="form.cartons_weight" type="number" placeholder="重量"></u-input>
				</u-form-item>
			</u-form>
		</view>
		<!-- SKU区域 -->
		<view class="custom-card">
			<view class="card-title sku-flex">
				<view>SKU</view>
				<view>
					<view class="sku-actions">
						<u-button size="mini" type="primary" @click="clearAllSku" text="清空"></u-button>
						<u-button size="mini" type="primary" @click="addSku" text="添加"></u-button>
					</view>
				</view>
			</view>
			<u-form :model="form" ref="uForm2">
				<template v-if="!loadingScan && form.skuList && form.skuList.length">
					<u-form-item v-for="(sku, index) in form.skuList" :label="`#${index + 1} SKU`" label-width="60"
						:key="sku.sku_code || index">

						<view class="dimension-input-row">
							<u-input v-model="sku.sku_code" size="mini" placeholder="SKU" style="margin-right: 5px;"></u-input>
							<u-input v-model="sku.quantity" size="mini" type="number" placeholder="数量"
								style="margin-right: 5px;"></u-input>
							<u-input v-model="sku.sku_qty" size="mini" type="number" placeholder="数量" style="margin-right: 5px;"
								disabled></u-input>
							<u-icon name="trash-fill" color="red" size="28" @click="form.skuList.splice(index, 1)"></u-icon>
						</view>
					</u-form-item>
				</template>
			</u-form>
			<u-empty v-if="!form.skuList || !form.skuList.length" text="暂无条码" mode="list"></u-empty>
		</view>

		<!-- 条码列表区 -->
		<view class="custom-card">
			<view class="card-title">条码列表</view>
			<u-empty v-if="boxes.length === 0" text="暂无条码" mode="list"></u-empty>
			<u-cell-group v-else :border="false">
				<u-cell v-for="(item, idx) in boxes" :key="idx" :title="item.code"
					:label="`箱号：${item.boxNo} 尺寸: ${item.cartons_length || '-'} x ${item.cartons_width || '-'} x ${item.cartons_height || '-'} cm，重量: ${item.cartons_weight || '-'} kg`">
				</u-cell>
			</u-cell-group>
		</view>

		<view style="height: 140rpx;"></view>

		<!-- 底部操作区 -->
		<view class="bottom-bar">
			<!-- <u-button type="primary" @click="addBarcode" :ripple="true" shape="circle" text="保存"></u-button> -->
			<u-button type="primary" @click="addBarcode" :ripple="true" shape="circle" text="保存并扫描下一件"></u-button>
		</view>
	</view>
</template>

<script>
import api from '../../api';
import LocationPop from "../../components/LocationPop.vue"
import _ from "lodash"

export default {
	components: {
		LocationPop
	},
	data() {
		return {
			form: {
				skuList: [],
				cartons_length: null,
				cartons_width: null,
				cartons_height: null,
				cartons_weight: null,
			},
			boxes: [],
			currentBoxIndex: 0,
			barcodeInput: '',
			showPicker: false,

			loadingLoaction: false,
			showLocationPicker: false,
			selectedLocationIds: [],
			locationList: [],
			loadingScan: false
		}
	},
	onLoad(options) {
		this.form.guid_order = options.order_guid;
		this.form.guid_warehouse = options.wms_guid;
	},
	computed: {
		currentBox() {
			if (!this.boxes[this.currentBoxIndex]) {
				return { locationList: [], length: '', width: '', height: '', sku: '', locationId: '', locationName: '' };
			}
			return this.boxes[this.currentBoxIndex]
		},
		boxPickerColumns() {
			return [this.boxes.map((_, i) => `箱 ${i + 1}`)]
		},
		isAllSelected() {
			return this.selectedLocationIds.length === this.locationList.length && this.locationList.length > 0
		}
	},
	methods: {
		clearAllSku() {
			this.form.skuList.length = 0;
		},
		addSku() {
			this.form.skuList.push({});
		},
		// 查询SKU数据（节流处理）
		onSearchSku: _.throttle(async function () {
			if (!this.form.cartons_no) {
				return;
			}
			this.loadingScan = true;
			const res = await api.inbound.getInboundList("cartonsSku", {
				data: {
					cartons_no: this.form.cartons_no
				}
			})
			const result = res.data.data;
			if (result) {
				this.form.cartons_length = result.box_length
				this.form.cartons_width = result.box_width
				this.form.cartons_height = result.box_height
				this.form.cartons_weight = result.box_weight
				this.form.skuList.length = 0;
				result.skuList.forEach(element => {
					element.quantity = element.sku_qty;
				});
				this.form.skuList.push(...result.skuList)
				// this.form.skuList = result.skuList ? [...result.skuList] : []
				this.$forceUpdate();//在这里，强制刷新之后，页面的结果变为'小红'
			}
			this.loadingScan = false;
		}, 1000),
		// 库位
		async onShowLocation() {
			this.showLocationPicker = true;
			this.locationList = [];
			this.loadingLoaction = true;
			const res = await api.wms.locationApi("locationList", {
				data: {
					guid_warehouse: "dc95299b-f8ff-4e0f-8481-60d32e1da83a"
				}
			}).finally(() => {
				this.loadingLoaction = false
			})
			this.locationList = res.data.data;
		},
		clearAll() {
			this.boxes = [];
		},
		scanCode() {
			uni.scanCode({
				success: (res) => {
					this.barcodeInput = res.result
					this.addBarcode()
				},
				fail: () => {
					uni.$u.toast('扫码失败');
				}
			})
		},
		async addBarcode() {
			const code = this.form.cartons_no.trim()
			const scanCode = this.barcodeInput.trim()
			if (!this.form.locationName) {
				uni.$u.toast("请选择库位")
				return;
			}

			// 显示 loading
			uni.showLoading({
				title: '处理中...'
			});

			const params = JSON.parse(JSON.stringify(Object.assign(this.form, { boxNo: code })));
			try {
				await api.inbound.getInboundList("createPickInfo", {
					data: {
						...params,
						cartons_no: this.form.cartons_no,
						skuList: this.form.skuList,
						cartons_length: this.form.cartons_length,
						cartons_width: this.form.cartons_width,
						cartons_height: this.form.cartons_height,
						cartons_weight: this.form.cartons_weight,
						location_code: this.form.locationName,
						guid_location: this.form.locationId
					}
				})

				// 处理成功后的逻辑
				if (code && !this.boxes.includes(code)) {
					this.boxes.push(params)
					this.barcodeInput = ''
					Object.assign(this.form, {
						sku: null,
						cartons_length: null,
						cartons_width: null,
						cartons_height: null,
						cartons_weight: null,
						cartons_no: null,
						cartons_no: scanCode || null,
						skuList: [],
					})
					uni.$u.toast('箱号添加成功')
				} else if (this.boxes.includes(code)) {
					uni.$u.toast('箱号已存在')
				} else {
					uni.$u.toast('箱号不能为空')
				}
			} catch (error) {
				uni.$u.toast('处理失败，请重试')
				console.error('addBarcode error:', error)
			} finally {
				// 隐藏 loading
				uni.hideLoading();
			}
		},
		removeBarcode(idx) {
			this.currentBox.locationList.splice(idx, 1)
			uni.$u.toast('删除成功');
		},
		addBox() {
			this.boxes.push({ locationList: [], length: '', width: '', height: '', sku: '', locationId: '', locationName: '' })
			this.currentBoxIndex = this.boxes.length - 1
			uni.$u.toast('已添加新箱');
		},
		switchBox() {
			if (this.boxes.length <= 1) {
				uni.$u.toast('当前只有一箱');
				return;
			}
			this.showPicker = true;
		},
		confirmSwitchBox(e) {
			this.currentBoxIndex = e.indexs[0];
			this.showPicker = false;
		},
		onLocationMultiConfirm() {
			// 多选库位确认
			const selected = this.locationList.filter(l => this.selectedLocationIds.includes(l.guid))
			this.form.locationId = this.selectedLocationIds.join(',')
			this.form.locationName = selected.map(l => l.location_code).join(', ')
			this.showLocationPicker = false
		},
		onScanLocation() {
			uni.scanCode({
				success: (res) => {
					const code = res.result.trim();
					// 假设扫码结果为库位ID
					const found = this.locationList.find(l => l.id === code || l.name === code);
					if (found) {
						this.currentBox.locationId = found.id;
						this.currentBox.locationName = found.name;
						uni.$u.toast('库位已填充');
					} else {
						this.currentBox.locationId = code;
						this.currentBox.locationName = code;
						uni.$u.toast('扫码库位未在列表，已直接填入');
					}
				},
				fail: () => {
					uni.$u.toast('扫码失败');
				}
			});
		},
		saveAll() {
			if (this.boxes.some(box => box.locationList.length === 0)) {
				uni.$u.toast('存在空箱，请检查');
				return;
			}
			uni.showModal({
				title: '提示',
				content: `共${this.boxes.length}箱，确认保存？`,
				success: async (res) => {
					if (res.confirm) {
						uni.showLoading({
							title: '保存中...'
						});
						await api.inbound.getInboundList("createPickInfo", {
							data: {
								cartons_no: this.form.cartons_no,
								skuList: this.form.skuList,
								cartons_length: this.form.cartons_length,
								cartons_width: this.form.cartons_width,
								cartons_height: this.form.cartons_height,
								cartons_weight: this.form.cartons_weight,
								location_code: this.form.locationName,
								guid_location: this.form.locationId
							}

						})
						uni.hideLoading();
						uni.$u.toast('批量保存成功!');
					}
				}
			})
		}
	}
}
</script>

<style lang="scss" scoped>
.container {
	padding: 8rpx;
	background-color: #f5f5f5;
	min-height: 100vh;
}

.custom-card {
	padding: 20rpx;
	margin-bottom: 8rpx;
}

.card-title {
	font-size: 22rpx;
	font-weight: 500;
	margin-bottom: 6rpx;
}

.sku-flex {
	display: flex;
	justify-content: space-between;
	align-items: center;
}

.sku-flex .sku-actions {
	display: flex;
	gap: 10rpx;
}

.u-form-item {
	padding: 1rpx 0;
	margin-bottom: 1rpx;
}

.u-form-item__body {
	font-size: 20rpx;
	padding: 0 !important;
}

.u-input__input {
	font-size: 20rpx;
	min-height: 36rpx;
	padding: 0 2rpx;
}

.dimension-input-row {
	display: flex;
	align-items: center;
}

.dimension-separator {
	margin: 0 1rpx;
	color: #909399;
	font-size: 16rpx;
}

.top-bar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 4rpx;

	.box-text {
		font-size: 22rpx;
		font-weight: 500;
	}

	.box-actions {
		display: flex;
		gap: 4rpx;
	}
}

.bottom-bar {
	position: fixed;
	bottom: 10rpx;
	left: 0;
	width: 100%;
	padding: 8rpx 10rpx;
	background-color: #ffffff;
	box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.05);
	box-sizing: border-box;
	padding-bottom: constant(safe-area-inset-bottom);
	padding-bottom: env(safe-area-inset-bottom);
	display: flex;
	gap: 10rpx;
}

.location-row {
	display: flex;
	align-items: center;
	gap: 8rpx;
	width: 100%;
}

.location-input {
	flex: 1;
	min-width: 0;
}

.location-scan-icon {
	margin-left: 6rpx;
	cursor: pointer;
	transition: color 0.2s;
}

.location-scan-icon:active {
	color: #1656a0;
}

.multi-location-popup {
	padding: 32rpx 24rpx 24rpx 24rpx;
	background: #fff;
	border-radius: 24rpx 24rpx 0 0;
}

.popup-title-row {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-bottom: 24rpx;
}

.popup-title {
	font-size: 28rpx;
	font-weight: bold;
	text-align: center;
}

.select-all-btn {
	margin-left: 24rpx;
}

.location-list-scroll {
	max-height: 400rpx;
	overflow-y: auto;
	margin-bottom: 24rpx;
}

.location-list-scroll .u-checkbox-group {
	display: flex;
	flex-wrap: wrap;
}

.location-checkbox-row {
	display: flex;
	align-items: center;
	margin-bottom: 18rpx;
	width: 100%;
}

.popup-actions {
	display: flex;
	justify-content: space-between;
	margin-top: 32rpx;
	gap: 24rpx;
}
</style>